/*
 * @todo: 工程vue.config配置 （nodejs语法）
 * @author: andy.ten@tom.com & xukaixing@hotmail.com
 * @Date: 2022-03-16 08:17:13
 * @LastEditors: andy.ten@tom.com
 * @LastEditTime: 2022-04-14 11:48:05
 * @version: 1.0.6
 * @copyright: copyright (c) 2022 andyten
 *  node: you can not copy and/or use and/or modify this program free,
 *  please reserve the segment above.Please mail me if you have any question.
 */

'use strict';
const path = require('path');
const settings = require('./src/settings');
const defaultConfig = require('./config');
var webpack = require('webpack');
const CompressionPlugin = require('compression-webpack-plugin');
const websiteTitle = settings.websiteTitle || 'Hawthorn Web Admin';
// devServer
const port = defaultConfig.dev.devServerPort;
const open = defaultConfig.dev.devServerOpen;
console.log(process.env.NODE_ENV);
function joinPath(dir) {
  return path.join(__dirname, dir);
}

module.exports = {
  // router是 hash 模式下因为有#，可使用：
  // publicPath: process.env.NODE_ENV === 'development' ? '/' : './',
  publicPath: defaultConfig.common.publicPath, // 即 BASE_URL
  outputDir: defaultConfig.common.outputDir,
  assetsDir: defaultConfig.common.assetsDir,
  lintOnSave: process.env.NODE_ENV === 'development',
  // 是否使用包含运行时编译器的 Vue 构建版本
  runtimeCompiler: false,
  productionSourceMap: defaultConfig.build.productionSourceMap,
  // 生成的 HTML 中的 <link rel="stylesheet"> 和 <script> 标签上启用 Subresource Integrity (SRI)
  integrity: false,
  devServer: {
    port: port,
    open: open,
    overlay: {
      warnings: false,
      errors: true
    }
  },
  configureWebpack: {
    name: websiteTitle,
    resolve: {
      alias: {
        '@': joinPath('src')
      }
    }
  },
  chainWebpack(config) {
    // it can improve the speed of the first screen, it is recommended to turn on preload

    config.plugin('preload').tap(() => [
      {
        rel: 'preload',
        // 黑名单 忽略runtime.js、热加载、sourceMap文件
        fileBlacklist: [/\.map$/, /hot-update\.js$/, /runtime\..*\.js$/],
        include: 'initial'
      }
    ]);

    // 取消prefetch和preload，相当于就是点一下，引入一下
    config.plugins.delete('prefetch');
    // config.plugins.delete('preload');

    config.plugin('ignore')
      .use(new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/));

    // set svg-sprite-loader
    config.module
      .rule('svg')
      .exclude.add(joinPath('src/assets/icons'))
      .end();
    config.module
      .rule('icons')
      .test(/\.svg$/)
      .include.add(joinPath('src/assets/icons'))
      .end()
      .use('svg-sprite-loader')
      .loader('svg-sprite-loader')
      .options({
        symbolId: 'icon-[name]'
      })
      .end();

    // set preserveWhitespace
    config.module
      .rule('vue')
      .use('vue-loader')
      .loader('vue-loader')
      .tap((options) => {
        options.compilerOptions.preserveWhitespace = true;
        return options;
      })
      .end();

    config
      .when(process.env.NODE_ENV === 'development',
        (config) => config.devtool('cheap-source-map')
      ).end();
    // 配置 sass-resources-loader 解决 组件中使用scss变量
    const oneOfsMap = config.module.rule('scss').oneOfs.store;
    oneOfsMap.forEach((item) => {
      item
        .use('sass-resources-loader')
        .loader('sass-resources-loader')
        .options({
          resources: './src/assets/styles/variables.scss'
        })
        .end();
    });

    config
      .when(process.env.NODE_ENV !== 'development',
        (config) => {
          config
            .plugin('ScriptExtHtmlWebpackPlugin')
            .after('html')
            .use('script-ext-html-webpack-plugin', [{
            // `runtime` must same as runtimeChunk name. default is `runtime`
              inline: /runtime\..*\.js$/
            }])
            .end();

          config.optimization.minimize(true).end();

          config
            .optimization.splitChunks({
              chunks: 'all',
              cacheGroups: {
                libs: {
                  name: 'app.vendor',
                  test: /[\\/]node_modules[\\/]/,
                  priority: -10,
                  chunks: 'initial'
                },
                echarts: {
                  name: 'app.echarts',
                  priority: 50,
                  test: module => /echarts/.test(module.context)
                },
                elementUI: {
                  name: 'app.elementUI',
                  priority: 50,
                  test: /[\\/]node_modules[\\/]element-ui/
                },
                hawthornUI: {
                  name: 'app.hawthornUI',
                  priority: 40,
                  test: /[\\/]node_modules[\\/]hawthorn-ui/
                },
                components: {
                  name: 'app.components',
                  test: joinPath('src/components'),
                  minChunks: 2,
                  priority: 10,
                  reuseExistingChunk: true
                }
              }
            });
          // 将chunk映射关联关系单独打包,生成 runtime.xx.js文件
          config.optimization.runtimeChunk('single');
        }
      ).end();
    if (defaultConfig.build.productionGzip === 'production')
      config.plugin('compressionPlugin').use(new CompressionPlugin({
        test: /\.(js|css|less)$/, // 匹配文件名
        algorithm: 'gzip',
        threshold: 10240, // 对超过10k的数据压缩
        minRatio: 0.8,
        deleteOriginalAssets: false // 不删除源文件
      }));
  },
  css: {
    loaderOptions: {
      sass: {
        additionalData: `@import "~@/assets/styles/element-variables.scss";`
      }
    }
  },
  transpileDependencies: [
    'vue-echarts',
    'resize-detector'
  ]
};
